package com.hqyj.javaSpringBoot.modules.account.service.impl;

import com.hqyj.javaSpringBoot.modules.account.dao.MenuDao;
import com.hqyj.javaSpringBoot.modules.account.entity.Menu;
import com.hqyj.javaSpringBoot.modules.account.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Override
    public List<Menu> getAllMenus() {
        List<Menu> allMenus = Optional.ofNullable(menuDao.getAllMenus()).orElse(Collections.emptyList());
        List<Menu> rootMenus = allMenus.stream()
                .filter(item -> item.getParentId() == 0)
                .collect(Collectors.toList());
        findSubItems(allMenus, rootMenus);
        return rootMenus;
    }

    // 递归封装多级菜单
    private void findSubItems(List<Menu> allMenus, List<Menu> rootMenus) {
        rootMenus.stream().forEach(item -> {
            List<Menu> subItems = new ArrayList<Menu>();
            allMenus.stream().forEach(it -> {
                if (it.getParentId() == item.getId()) {
                    subItems.add(it);
                }
            });
            findSubItems(allMenus, subItems);
            item.setSubItems(subItems);
        });
    }

    @Override
    public List<Menu> getMenusByUserId(int userId) {
        List<Menu> allMenus = Optional
                .ofNullable(menuDao.getMenusByUserId(userId))
                .orElse(Collections.emptyList());
        List<Menu> rootMenus = allMenus.stream()
                .filter(item -> item.getParentId() == 0)
                .collect(Collectors.toList());
        findSubItems(allMenus, rootMenus);
        return rootMenus;
    }

}
